﻿#region Usings

using System;
using System.IO;
using System.Runtime.Serialization.Json;
using System.Text;

#endregion

namespace SilverBox.Extensions
{
    public static class JsonExtensions
    {
        /// <summary>
        /// Deserialize an object from a string that contains the json object serialized.
        /// </summary>
        /// <typeparam name="T">Object type which you want to return.</typeparam>
        /// <param name="jsonString">Json Object to deserialize.</param>
        /// <returns>"T" object deserialized from the jsonString.</returns>
        public static T DeserializeFromJson<T>(this string jsonString)
        {
            try
            {
                using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(jsonString)))
                {
                    var serializer = new DataContractJsonSerializer(typeof (T));
                    return (T) serializer.ReadObject(ms);
                }
            }
            catch (Exception ex)
            {
                throw new SilverBoxSerializationException(
                    "Couldn't deserialize from Json string. See inner for more details.", ex);
            }
        }

        /// <summary>
        /// Serialize an object to a string that contains the json object.
        /// </summary>
        /// <param name="objectToSerialize">Object to be serialized.</param>
        /// <returns>A string that contains the json object serialized.</returns>
        public static string SerializeToJsonString(this object objectToSerialize)
        {
            try
            {
                using (var ms = new MemoryStream())
                {
                    var serializer = new DataContractJsonSerializer(objectToSerialize.GetType());
                    serializer.WriteObject(ms, objectToSerialize);
                    ms.Position = 0;
                    using (var reader = new StreamReader(ms))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                throw new SilverBoxSerializationException(
                    "Couldn't serialize from Json string. See inner for more details.", ex);
            }
        }
    }
}